package org.holynite.fieldmanage.managed.controller

import org.holynite.fieldmanage.ejbs.AdministratorManagement
import org.holynite.fieldmanage.ejbs.AuthorizationManagement
import org.holynite.fieldmanage.entities.Administrator
import org.holynite.fieldmanage.entities.AdministratorRole
import org.holynite.fieldmanage.managed.model.AdministratorFormBean
import org.holynite.fieldmanage.managed.model.AdministratorsBean
import org.holynite.fieldmanage.managed.support.RolesBean
import org.holynite.fieldmanage.utils.LocaleString

import javax.annotation.PostConstruct
import javax.ejb.EJB
import javax.faces.application.FacesMessage
import javax.faces.bean.ManagedBean
import javax.faces.bean.ManagedProperty
import javax.faces.bean.RequestScoped
import javax.faces.component.UIComponent
import javax.faces.component.UIInput
import javax.faces.context.FacesContext
import javax.faces.event.ValueChangeEvent
import javax.faces.model.SelectItem
import javax.faces.validator.ValidatorException
import javax.inject.Inject

/**
 * Created by midnite on 15/1/16.
 */
@ManagedBean
@RequestScoped
class AdminBean {

	@EJB(beanName = "adminRoleControl")
	AuthorizationManagement roleService
	@EJB(beanName = "adminControl")
	AdministratorManagement adminService
    @ManagedProperty("#{administratorFormBean}")
    AdministratorFormBean adminForm
    @ManagedProperty("#{administratorsBean}")
    AdministratorsBean adminsBean
    @ManagedProperty("#{rolesBean}")
    RolesBean rolesBean
	@Inject
	LocaleString locale

	AdminBean() {
	}

	@PostConstruct
	void fillData() {
	}

	def searchAdmins() {
		adminsBean.reloadAdministrators(adminForm.searchKeyword)
		null
	}

	def saveAdministrator() {
		if (adminForm.addMode) {
			def adminRole = rolesBean.roles.find { it.svrid.equals(adminForm.selectedRole) }
			def newAdmin = new Administrator(
                    workdId: adminForm.adminWorkId, name: adminForm.adminName,
                    password: adminForm.adminPassword, create: Calendar.instance.time,
				    role: adminRole, disabled: adminForm.adminDisabled
			)
			adminService.addAdministrator(newAdmin)
		} else {
            def adminRole = rolesBean.roles.find { it.svrid.equals(adminForm.selectedRole) }
            def selectedAdmin = adminsBean.admins.find { it.workdId.equals(adminForm.selectedAdmin) }
			selectedAdmin.name = adminForm.adminName
			if (adminForm.adminPassword.length() > 0) selectedAdmin.password = adminForm.adminPassword
			selectedAdmin.disabled = adminForm.adminDisabled
			selectedAdmin.role = adminRole
			adminService.saveAdministrator(selectedAdmin)
		}
        adminForm.clearForm()
        adminForm.clearSearch()
        adminsBean.findAdministrator(adminForm.searchKeyword)
		null
	}

	def removeAdministrator() {
        if (adminForm.addMode) throw new Exception(locale.fetch("warningDeleteInNew"))
		adminService.removeAdministrator(adminForm.selectedAdmin)
        adminForm.clearForm()
		null
	}

    void validateWorkId(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (!adminForm.addMode) return
        if (!context || !component) throw new NullPointerException()
        if (!(component instanceof UIInput) || value == null) return
        def existenceCheck = adminService.checkWorkIdUsable(value as String)
        if (!existenceCheck) throw new ValidatorException(new FacesMessage(locale.fetch("adminManageWorkIdUnusable")))
    }
}
